<?php

namespace app\util;

/*
 * 发送微信公众号模板消息
 */

class WxMessage
{
    //appid
    const APPID = 'wx32e16f8171dbf3ea';

    //secret
    const SECRET = 'b38faa2e2ab511b65d8ff4b4e6bc4acd';

    /*
     * 公众号获取 access_token
     * author xfwed 
     * date 2021.09.26
     */

    public function getAccessToken() {
        $AppID = self::APPID;
        $APPSecret = self::SECRET;
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$AppID."&secret=".$APPSecret;
       
        $access_token_time = session('WX_ACCESS_TOKEN_TIME');
        $a = $access_token_time + 7200;
        if($access_token_time && $a > time()){
            $access_token = session('WX_ACCESS_TOKEN');
        }  else {
            $relust = Utils::curlGet($url);
            $relust = json_decode($relust,true);
            session("WX_ACCESS_TOKEN", $relust['access_token']);
            session("WX_ACCESS_TOKEN_TIME", time());
            $access_token = $relust['access_token'];
        }
        return $access_token;
        //return Utils::ajaxReturn(0, '成功', $relust['access_token']);
        
    }

    /*
     * 发送公众号模板消息
     * author xfwed 
     * date 2021.09.26
     */

    public function sendWechatMessage($postFields) {
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
//        $postFields['touser'] = $openid;
//        $postFields['template_id'] = $template_id;
//        $postFields['url'] = 'http://weixin.qq.com/download';
//        $postFields['topcolor'] = '#FF0000';
//        $postFields['data']['first']['value'] = '测试测试';
//        $postFields['data']['keyword1']['value'] = 'YCN000001707250017';
//        $postFields['data']['keyword2']['value'] = '2017年7月25日 17';
//        $postFields['data']['remark']['value'] = '您可以同经纪人取得联系，进一步明确需求，并且通过“需求确认”选定经纪人！';
        
        return $relust = Utils::curlPost($url, $postFields);
    }
    
    /*
     * 获取用户列表
     * author xfwed 
     * date 2021.09.26
     */

    public function weChatCtm($next_openid) {
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$access_token."&next_openid=".$next_openid;
        
        return $relust = Utils::curlGet($url);
    }
    /*
     * 获取用户基本信息(UnionID机制)
     * author xfwed 
     * date 2021.09.26
     */

    public function weChatCtmInfo($openid) {
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
        return $relust = Utils::curlGet($url);
    }
    

}